package com.example.controller;

import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    // 用户列表页面
    @GetMapping("/list")
    public String list(Model model) {
        List<User> users = userService.getAllUsers();
        model.addAttribute("users", users);
        return "user/list";
    }

    // 用户详情页面
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable Integer id, Model model) {
        User user = userService.getUserById(id);
        model.addAttribute("user", user);
        return "user/detail";
    }

    // 添加用户页面
    @GetMapping("/add")
    public String addPage() {
        return "user/add";
    }

    // 添加用户
    @PostMapping("/add")
    @ResponseBody
    public String add(User user) {
        boolean result = userService.addUser(user);
        return result ? "success" : "failed";
    }

    // 编辑用户页面
    @GetMapping("/edit/{id}")
    public String editPage(@PathVariable Integer id, Model model) {
        User user = userService.getUserById(id);
        model.addAttribute("user", user);
        return "user/edit";
    }

    // 更新用户
    @PostMapping("/update")
    @ResponseBody
    public String update(User user) {
        boolean result = userService.updateUser(user);
        return result ? "success" : "failed";
    }

    // 删除用户
    @GetMapping("/delete/{id}")
    @ResponseBody
    public String delete(@PathVariable Integer id) {
        boolean result = userService.deleteUser(id);
        return result ? "success" : "failed";
    }
}
